const jq_chat = $("#chat");
const jq_tool = $("#tool");
const jq_send = $("#send");
const jq_face = $("#face");
const jq_voice = $("#voice");
const jq_inputText = $("#inputText");
const jq_function = $("#function");
const emojiContainer = $("#emojiContainer");
var imageUrl = ""; // 上传的图片地址

// 功能栏
// const element = document.getElementById('content');

let flag = true;
jq_tool.click(() => {
  if (flag) {
    jq_chat.css({
      height: "54%",
    });
  } else {
    jq_chat.css({
      height: "90%",
    });
  }
  flag = !flag;
  emojiContainer.hide(400);
  jq_function.slideToggle(400);
});

// 相机弹窗交互

const jq_camera = $("#camera-icon");

// 打开弹窗
jq_camera.click(() => {
  $("#cameraModal").modal();
  $("#preview-area").html("");
});

// 点击拍照（只允许图片）
$("#take-photo").on("click", function () {
  $("#upload-input").attr("accept", "image/*").click(); // 限制为图片
});

// 点击上传文件（只允许特定文件类型）
$("#upload-file").on("click", function () {
  // $("#upload-input").attr("accept", ".doc,.docx").click(); // 限制为文档
  $("#upload-input").attr("accept", "image/*").click(); // 限制为图片
});

// 上传文件/图片后的处理
$("#upload-input").on("change", function (event) {
  const file = event.target.files[0]; // 获取文件

  if (file) {
    const fileType = file.type;
    const reader = new FileReader();

    reader.onload = function (e) {
      // 创建一个预览项
      const previewItem = $("<div>").addClass("preview-item");

      if (fileType.startsWith("image/")) {
        // 图片预览
        const img = $("<img>")
          .attr("src", e.target.result)
          .attr("alt", file.name);
        previewItem.append(img);
      } else {
        // 文件名预览
        const fileName = $("<p>")
          .addClass("file-name")
          .text(`文件名：${file.name}`);
        previewItem.append(fileName);
      }

      // 添加到预览区域
      $("#preview-area").html("");
      $("#preview-area").append(previewItem);
      imageUrl = e.target.result;
    };

    // 根据文件类型读取内容
    if (fileType.startsWith("image/")) {
      reader.readAsDataURL(file);
    } else {
      reader.readAsText(file);
    }
  } else {
    alert("未选择任何文件！");
  }
});

// 发送图片
const jq_confirmUploadImage = $("#confirmUploadImage");
jq_confirmUploadImage.click(() => {
  console.log("发送图片");
  addContent(
    `
    <div class="image icon">
        <img src="${imageUrl}" />
    </div>
    `
  );
  $("#cameraModal").modal("hide");
});

// 表情包
const emojiCodes = [
  "1F604", // 😄
  "1F603", // 😃
  "1F600", // 😀
  "1F601", // 😁
  "1F606", // 😆
  "1F605", // 😅
  "1F602", // 😂
  "1F923", // 🤣
  "1F607", // 😊
  "1F60D", // 😇
  "1F618", // 😍
  "1F61A", // 😘
  "1F619", // 😚
  "1F60B", // 😙
  "1F61C", // 😋
  "1F61D", // 😜
  "1F60E", // 😝
  "1F917", // 😎
  "1F929", // 🤗
  "1F60A", // 🤩
];
let face = true;
let isEmojiGenerated = false;
jq_face.click(() => {
  if (face) {
    jq_chat.css({
      height: "70%",
    });
  } else {
    jq_chat.css({
      height: "90%",
    });
  }
  face = !face;
  emojiContainer.slideToggle(400);
  jq_function.hide();

  if (!isEmojiGenerated) {
    emojiCodes.forEach((code) => {
      const emoji = $("<span>")
        .addClass("emoji")
        .html(`&#x${code}`)
        .attr("code", code);
      emojiContainer.append(emoji);
    });
    isEmojiGenerated = true;
  }

  emojiContainer.off("click", ".emoji");
  emojiContainer.on("click", ".emoji", function (e) {
    e.stopPropagation(); // 阻止事件冒泡
    const newEmoji = e.target.attributes[1].value;
    addContent(`&#x${newEmoji}`);
  });
  // addContent(`&#x1F600; &#x1F60D; &#x1F973; &#x1F389; &#x1F355;`);
});

// 发送文本
jq_send.click(() => {
  const text = jq_inputText.val();
  if (!text) {
    alert("请输入内容");
    return;
  }
  addContent(text);
  jq_inputText.val("");
});

// 监听输入框的 keydown 事件
$("#inputText").on("keydown", function (event) {
  // 检查是否按下了回车键（ keyCode 13）
  if (event.keyCode === 13) {
    // 阻止默认行为（例如换行）
    event.preventDefault();

    // 获取输入框的值
    const message = $(this).val();

    // 检查消息是否为空
    if (message.trim() !== "") {
      // 发送消息（这里只是一个示例，您可以根据实际需求发送消息）
      console.log("发送的消息:", message);
      addContent(message);
      // 清空输入框
      $(this).val("");
    } else {
      // 如果消息为空，给出提示
      alert("请输入内容");
    }
  }
});

// 发送语音
// jq_voice.click(() => {
//   addContent(
//     `
//     <div class="voice icon">
//         <img src="../../public/images/v1.png" />
//     </div>
//     <div class="c-m-l-10">6''</div>
//     `,
//     "voiceBtn"
//   );
//   const jq_voiceBtn = $("#voiceBtn");
//   jq_voiceBtn.click(() => {
//     console.log("播放语音");
//   });
// });

const sendVoice = () => {
  addContent(
    `
    <div class="voice icon">
        <img src="../../public/images/v1.png" />
    </div>
    <div class="c-m-l-10">6''</div>
    `,
    "voiceBtn"
  );
  const jq_voiceBtn = $("#voiceBtn");
  jq_voiceBtn.click(() => {
    console.log("播放语音");
  });
};

const voiceButton = $("#voice"); //录音按钮
const mask = $(".mask");
const recordingPopup = $("#recordingPopup");
const cancelButton = $("#cancelButton");
const voiceMessages = $("#voiceMessages");
const waveformContainer = $("#waveformContainer");

let isRecording = false; // 标记是否正在录音

// $("#record-button").hide()
// voiceButton.on("click", function (e) {
//   // e.preventDefault();
//   // isRecording = true;
//   // recordingPopup.show();
//   // mask.show();
//   // createWaveformBars();
//   $("#StrText").hide()
//   $("#record-button").show()

// });
document.addEventListener("DOMContentLoaded", (event) => {
  const recordButton = document.getElementById("record-button");

  let mediaRecorder;
  let audioChunks = [];
  let isRecording = false;
  let mouseDown = false; // 用于跟踪鼠标是否按下
  let isRecordButtonVisible = false; // 用于跟踪记录按钮是否可见
  // 检查浏览器支持
  if (!("mediaDevices" in navigator)) {
    console.error("当前浏览器不支持 mediaDevices");

    alert("当前浏览器不支持录音功能，请使用支持的浏览器。");
    return;
  }
  // 请求用户麦克风权限
  navigator.mediaDevices
    .getUserMedia({ audio: true })
    .then((stream) => {
      mediaRecorder = new MediaRecorder(stream);

      mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          audioChunks.push(event.data);
        }
      };

      mediaRecorder.onstop = () => {
        const audioBlob = new Blob(audioChunks, { type: "audio/webm" });
        audioChunks = [];

        const audioUrl = URL.createObjectURL(audioBlob);
        const audio = document.createElement("audio");
        audio.controls = false;
        audio.src = audioUrl;

        // 生成唯一 ID
        const audioId = "audio-" + Date.now();

        // 将音频元素插入到 DOM 中，但不显示
        audio.id = audioId;
        document.body.appendChild(audio);

        // 创建包含音频播放功能的 HTML 字符串
        const contentHtml = `
          <div class="voice icon">
            <img src="../../public/images/v1.png" class="play-pause-btn" data-audio-id="${audioId}" />
          </div>
          <div class="c-m-l-10">6''</div>
        `;
        addContent(contentHtml);
        // 添加内容到页面

        // 为图片元素添加点击事件监听器
        const playPauseBtn = document.querySelector(
          `.play-pause-btn[data-audio-id="${audioId}"]`
        );
        playPauseBtn.addEventListener("click", (e) => {
          const audioElement = document.getElementById(
            e.target.dataset.audioId
          );
          if (audioElement.paused) {
            audioElement.play();
            e.target.setAttribute("src", "../../public/images/v2.png"); // 更换为播放中的图标
          } else {
            audioElement.pause();
            e.target.setAttribute("src", "../../public/images/v1.png"); // 更换为暂停的图标
          }
        });

        recordingPopup.hide();
        mask.hide();
      };

      // 录音开始的逻辑
      const startRecording = (e) => {
        e.preventDefault();
        isRecording = true;
        recordingPopup.show();
        // mask.show();
        createWaveformBars();
        mediaRecorder.start();
      };

      // 录音停止的逻辑
      const stopRecording = (e) => {
        if (mediaRecorder.state === "recording") {
          isRecording = false;

          mediaRecorder.stop();
        }
      };

      // 绑定事件
      recordButton.addEventListener("mousedown", (e) => {
        mouseDown = true;
        startRecording(e);
      });

      recordButton.addEventListener("mouseup", (e) => {
        mouseDown = false;
        stopRecording(e);
      });

      recordButton.addEventListener("mouseleave", (e) => {
        if (mouseDown) {
          mouseDown = false;
          stopRecording(e);
        }
      });

      // 对于移动设备
      recordButton.addEventListener("touchstart", (e) => {
        e.preventDefault();
        startRecording(e);
      });

      recordButton.addEventListener("touchend", (e) => {
        e.preventDefault();
        stopRecording(e);
      });

      // 点击 voiceButton 显示 record-button 按钮
      $("#voice").on("click", function (e) {
        if (isRecordButtonVisible) {
          $("#StrText").show();
          $("#record-button").hide();
        } else {
          $("#StrText").hide();
          $("#record-button").show();
        }
        isRecordButtonVisible = !isRecordButtonVisible;
      });
    })
    .catch((error) => {
      console.error("无法访问麦克风:", error);
    });
});
$("#record-button").hide();
// voiceButton.on("mousedown", function (e) {
//   e.preventDefault();
//   isRecording = true;
//   recordingPopup.show();
//   mask.show();
//   createWaveformBars();
// });

// cancelButton.on("click", function () {
//   isRecording = false;
//   recordingPopup.hide();
//   mask.hide();
//   //sendVoice()
// });

// voiceButton.on("mouseup", function () {
//   if (isRecording) {
//     isRecording = false;
//     $(".waveform-bar", waveformContainer).each(function () {
//       $(this).css("animation-playState", "paused");
//     });
//     recordingPopup.hide();
//     mask.hide();

//     addContent(
//       `
//       <div class="voice icon">
//           <img src="../../public/images/v1.png" />
//       </div>
//       <div class="c-m-l-10">6''</div>
//       `,
//       "voiceBtn"
//     );
//   }
// });
function createWaveformBars() {
  const barHeights = [10, 20, 30, 40, 50];
  const barDelays = [0, 0.1, 0.2, 0.3, 0.4];
  const barDurations = [0.8, 0.9, 1, 1.1, 1.2];

  for (let i = 0; i < 5; i++) {
    const bar = $("<div>").addClass("waveform-bar");
    bar.css({
      height: `${barHeights[i]}px`,
      left: `${i * 15}px`,
      "animation-delay": `${barDelays[i]}s`,
      "animation-duration": `${barDurations[i]}s`,
      "animation-playState": "running",
    });
    waveformContainer.append(bar);
  }
}

const addContent = (text, id) => {
  const jq_list_items = $("#list .item");
  const lastChild = jq_list_items.last()[0];
  const template = `<div class="newface item core-flex-center core-flex-justify-between" id="${id}">
    <div class="core-flex-center core-flex-justify-end" style="width:100%;">
        <div
        class="talk reply bg-white-color core-flex-center core-flex-align-start"
        >
       ${text}
        </div>
        <div class="icon">
        <img src="../../public/images/a3.png" />
        </div>
    </div>
</div>`;
  lastChild.insertAdjacentHTML("afterend", template);
  jq_chat[0].scrollTo({
    top: jq_chat[0].scrollHeight,
    behavior: "smooth",
  });
};
